package com.zgw.fireline.design;

import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.registry.LocateRegistry;

import org.eclipse.ui.IStartup;
import org.eclipse.ui.internal.WorkbenchPlugin;

import com.zgw.fireline.design.service.IDesignCommonService;

public class RMIService implements IStartup {
	private int port = 9693;
	private String rmiPath = "rmi://localhost:" + port + "/";

	public RMIService() {

	}

	private void initialize() {
		try {
			LocateRegistry.createRegistry(port);
			bind(IDesignCommonService.class, new DesignCommonServiceImpl());
			System.out.println("RMI服务已启动: " + rmiPath);
		} catch (Exception e) {
			e.printStackTrace();
			WorkbenchPlugin.log(e);
		}
	}

	private <T extends Remote> void bind(Class<T> interfaceClass, T impl)
			throws Exception {
		Naming.bind(rmiPath + interfaceClass.getName(), impl);
	}

	/**
	 * @see 启动项初始化 </p> 由于RCP特殊的类装载机制 ,代码中需要设置安全管理器:{@link RMISecurityManager}
	 *      并且改当前变线程的 类加载器
	 * */
	public void earlyStartup() {
		SecurityManager secMan = System.getSecurityManager();
		ClassLoader cl = Thread.currentThread().getContextClassLoader();
		try {
			System.setSecurityManager(new RMISecurityManager());
			ClassLoader parent = this.getClass().getClassLoader();
			Thread.currentThread().setContextClassLoader(parent);
			// 初始化RMI服务
			initialize();
		} finally {
			System.setSecurityManager(secMan);
			Thread.currentThread().setContextClassLoader(cl);
		}

	}

	public static void main(String[] args) {
		RMIService service = new RMIService();
		service.initialize();
	}
}
